// 运行时配置
import { requestConfig } from "./requestConfig";
import { LinkOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { SettingDrawer, ProBreadcrumb } from '@ant-design/pro-components';
import { history, Link, useModel } from '@umijs/max';
import type { RuntimeConfig, RunTimeLayoutConfig } from '@umijs/max';
// 界面配置
import defaultSettings from '../config/defaultSettings';
// 获取用户信息(后端从 gAuth 中获取)
import { queryCurrentUser } from '@/services/api_user';
import { AvatarDropdown } from '@/components/Header/AvatarDropdown';
import Footer from "./components/Footer";
import type { UserInfo } from "./services/types";

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request = {
  ...requestConfig,
};


const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

/**
 * 每个页面加载时调用: 获取登录用户信息(取不到则转到登录页)
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: UserInfo;
  loading?: boolean;
  fetchUserInfo?: () => Promise<UserInfo | undefined>;
}> {
  // 如果不是登录页面，执行
  const location = (history as any).location;

  const fetchUserInfo = async () => {
    // 本地调用 apiFox mack 数据
    // if (REACT_APP_ENV === 'local') return { name: 'admin' } as UserInfo;

    const { success, data } = await queryCurrentUser({
      skipErrorHandler: true,
    })
    if (!success && location.pathname !== loginPath) { // 取不到用户信息且不在登录页
      history.push(loginPath);
      return undefined;
    }
    return data as UserInfo;
  };

  if (!location.pathname.startsWith(loginPath)) {
    // url 后有时会有 / 与 loginPath 不匹配
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser, // 页面加载时判断是否登录成功
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

/** 
 * @name layout 配置，用于配置布局相关的内容。头像,水印,页脚,页面切换,说明文档连接,(dev时显示)配置抽屉
 * @doc https://procomponents.ant.design/components/layout
 */
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  // const { initialState, setInitialState } = useModel('@@initialState');
  return {
    // logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    logo: '/favicon.jpg',
    menu: {
      locale: false,
    },

    // menuRender: false, // 禁用菜单

    //头像
    avatarProps: {
      // 头像地址
      src: initialState?.currentUser?.avatar,
      // 头像呢称
      title: initialState?.currentUser?.name ?? '未登录',
      render: (_: any, avatarChildren: any) => {
        // 点击头像显示的下拉菜单
        return <AvatarDropdown>{avatarChildren} </AvatarDropdown>;
      },
    },
    // 页面水印
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    // 默认布局调整
    // 顶步导航 layout:'mix' 时有效
    // headerContentRender: () => <ProBreadcrumb />,
    // 右侧
    // rightContentRender: () => <RightContent />,
    // 渲染底部
    footerRender: () => <Footer />,
    // menuHeaderRender: undefined,
    // 页面切换
    onPageChange: () => {
      const location = (history as any).location;

      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: isDev // 开发时显示文档连接
      ? [
        <Link key="openapi" to="/umi/plugin/openapi" target="_blank" >
          <LinkOutlined />
          < span > OpenAPI 文档 </span>
        </Link>,
      ]
      : [],


    // 自定义 403 页面, 无权限时显示的页面
    unAccessible: <div>unAccessible </div>,

    // 增加一个 loading 的状态
    childrenRender: (children: any) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          <ProBreadcrumb />
          {children}
          {
            isDev && ( // 开发模式显示"配置抽屉"
              <SettingDrawer
                disableUrlParams
                enableDarkTheme
                settings={initialState?.settings}
                onSettingChange={(settings) => {
                  setInitialState((preInitialState: any) => ({
                    ...preInitialState,
                    settings,
                  }));
                }}
              />
            )}
        </>
      );
    },
    ...initialState?.settings,
  };
};
